package com.zthz.douxing

import com.google.common.eventbus.AsyncEventBus
import com.google.common.eventbus.EventBus
import groovy.transform.CompileStatic
import groovy.transform.TypeCheckingMode

import java.util.concurrent.ExecutorService

/**
 * Guava的服务的代理。非常容易就实现了一个代理模式。
 */
class EventBusService {
    EventBus eventBus;

    public EventBusService(){
        //这一空构造一定要有，不然就会走methodMissing方法了。
        ExecutorService executorService = java.util.concurrent.Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1)
        eventBus = new AsyncEventBus("EventBusService", executorService)
    }

    @CompileStatic(TypeCheckingMode.SKIP)
    def methodMissing(String name, Object args) {
        log.debug("the name of method call is ${name}")
        def argsTypes = []
        args.each{ it ->
            argsTypes << it.class
        }
        //只要判断args是不是数组就可以
        try{
            if(eventBus.metaClass.respondsTo(eventBus, name, argsTypes)){
                return eventBus.metaClass.invokeMethod(eventBus, name, args)
            } else {
                throw new MissingMethodException(name, eventBus, args)
            }
        }catch (Exception e){
            log.debug(e.getMessage(),e.printStackTrace())
        }

    }

}
